package xuanzhen.pro.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import sun.misc.BASE64Decoder;
import xuanzhen.wx.pojo.Jsticket;

import xuanzhen.pro.pojo.Relay;
import xuanzhen.pro.service.RelayService;

import xuanzhen.wx.service.CoreService;
import xuanzhen.wx.util.EmojiFilter;

@Controller
@RequestMapping("/relay")
public class RelayController  {
	@Resource
	RelayService relayService;
	@Resource
	CoreService coreService;

	File tmpDir = null;// 初始化上传文件的临时存放目录
	File saveDir = null;// 初始化上传文件后的保存目录

	/**
	 * 添加接力
	 */
	@RequestMapping(value = "/addRelay", method = RequestMethod.POST)
	public String saveRelay(@ModelAttribute Relay relay,  Model model,
			HttpSession session, HttpServletRequest req, HttpServletResponse response) throws Exception {

		
		  // 获取时间戳 
		long timestamp = System.currentTimeMillis() / 1000;
		  session.setAttribute("timestamp", timestamp); // 生成随机字符串 
		  String  noncestr = RandomStringUtils.randomAlphanumeric(16);
		  session.setAttribute("noncestr", noncestr); 
		  String code=""; 
		  code =  (String)session.getAttribute("code"); // 当前网页url 
		  String url=""; 
		  url =  req.getScheme() + "://" + req.getServerName() + req.getRequestURI();
		  if (req.getQueryString() != null) { 
			  url += "?" +  req.getQueryString(); } 
		  System.out.println(url); 
		  Jsticket  ticket=(Jsticket) session.getAttribute("ticket"); // 签名
		  String  signature = coreService.getSignature(url, timestamp + "", noncestr,ticket.getTicket()); 
		  session.setAttribute("signature", signature);
		 

		/*if (photo[0].getOriginalFilename() != null) {
			long times = System.currentTimeMillis();
			String p1 = "upload/" + relay.getRelayNo() + "_" + photo[0].getName() + "_"
					+ photo[0].getOriginalFilename();
			relay.setPhoto1(p1);
		}
		if (photo[1].getOriginalFilename() != null) {
			long times = System.currentTimeMillis();
			String p2 = "upload/" + relay.getRelayNo() + "_" + photo[1].getName() + "_"
					+ photo[1].getOriginalFilename();
			relay.setPhoto2(p2);
		}
		if (photo[2].getOriginalFilename() != null) {
			long times = System.currentTimeMillis();
			String p3 = "upload/" + relay.getRelayNo() + "_" + photo[2].getName() + "_"
					+ photo[2].getOriginalFilename();
			relay.setPhoto3(p3);
		}*/
		 String name= EmojiFilter.filterEmoji(relay.getSponsor());
		 relay.setSponsor(name);
		String tag = relayService.addRelay(relay);
		session.setAttribute("address", relay.getRelayAddress());
		if (tag != null) {
			return "begin";
		} else {
			return "error";
		}

	}

	/**
	 * 上传
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public String uploadIMG(String userfile,String fileFormat, HttpSession session, HttpServletRequest req) throws Exception {

		/*
		 * tmpDir = new File("car2go_imgs/tmpdir"); saveDir = new
		 * File("car2go_imgs/updir"); if (!tmpDir.isDirectory()) tmpDir.mkdir();
		 * if (!saveDir.isDirectory()) saveDir.mkdir();
		 */
		
		
		
		
		
		
		String tag = (String) session.getAttribute("relayNo");
		/* String noce = RandomStringUtils.randomAlphanumeric(6); */
		long currentTimestamp = System.currentTimeMillis();
		 SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
		    String d = format.format(currentTimestamp);  
		String dd =d.substring(0, 10);
		System.out.println(dd);
		saveDir = new File(req.getServletContext().getRealPath("upload")+"/"+dd);
		if (!saveDir.isDirectory())
			saveDir.mkdir();
		
		

		String fileName = tag + "_" + currentTimestamp+"."+fileFormat;
/*		FileUtils.copyInputStreamToFile(userfile.getInputStream(),
				new File(req.getServletContext().getRealPath("upload")+"/"+dd, fileName));*/
		GenerateImage( userfile, req.getServletContext().getRealPath("upload")+"/"+dd+"/"+fileName);
//GenerateImage(String imgStr, String imgFilePath)
//		System.out.print("upload succeed");
		String s = "upload/" +dd+"/"+ fileName;
		return s;
	}
	public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

	/**
	 * 完成接力
	 */
	@RequestMapping(value = "/updateRelay", method = RequestMethod.POST)
	public String updateRelay(@ModelAttribute Relay relay, Model model,
			HttpSession session, HttpServletRequest req, HttpServletResponse response) throws Exception {

		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		String code = "";
		code = (String) session.getAttribute("code");
		// 当前网页url
		String url = "";
		url = req.getScheme() + "://" + req.getServerName() + req.getRequestURI();
		if (req.getQueryString() != null) {
			url += "?" + req.getQueryString();
		}
		System.out.println(url);
		Jsticket ticket = (Jsticket) session.getAttribute("ticket");
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);

		/*if (pic[0].getOriginalFilename() != null) {
			String p1 = "upload/" + relay.getRelayNo() + "_" + pic[0].getOriginalFilename();
			relay.setPic1(p1);
		}
		if (pic[1].getOriginalFilename() != null) {
			String p2 = "upload/" + relay.getRelayNo() + "_" + pic[1].getOriginalFilename();
			relay.setPic2(p2);
		}
		if (pic[2].getOriginalFilename() != null) {
			String p3 = "upload/" + relay.getRelayNo() + "_" + pic[2].getOriginalFilename();
			relay.setPic3(p3);
		}*/
		 String name= EmojiFilter.filterEmoji(relay.getRecipient());
		 relay.setRecipient(name);
		relay.setRelayState("finish");
		Relay re = relayService.selectRelayByRelayNo(relay.getRelayNo());
		String tag = re.getRelayState();
		if ("normal".equals(tag)) {
			Relay relay2 = relayService.updateRelay(relay);
			return "wanc";
		} else {
			return "over";
		}

	}

	/**
	 * 接收人接收分享页面
	 */
	@RequestMapping(value = "/recet", method = RequestMethod.GET)
	public String recet(@ModelAttribute Relay relay, MultipartFile userfile, Model model, HttpSession session,
			HttpServletRequest req, HttpServletResponse response) throws Exception {

		return "index";
	}
}
